"""
使用装饰器来为斐波那契函数添加缓存
"""


cache = {}


def cache_deco(func):
    global cache

    def wrapper(*args, **kwargs):
        if args[0] in cache:
            print('cache中有值')
            return cache[args[0]]
        result = func(args[0])
        cache[args[0]] = result
        return result
    return wrapper


@cache_deco
def fib(n):
    print('called')

    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)


# 嵌套函数enclosed
def make_average():
    # 自由变量
    series = []

    def average(value):
        series.append(value)
        total = sum(series)
        return total / len(series)
    return average


def make_average2():
    # 自由变量  不可变变量需要nonlocal关键词修饰
    length = 0
    total = 0

    def average(value):
        nonlocal length
        nonlocal total
        length += 1
        total += value
        return total / length
    return average


# 生成器
def foo():
    for x in [1, 2, 3]:
        yield x
        print(f'for 进来了{x}')


if __name__ == '__main__':
    print(f'cache前：{fib(10)}')
    print(f'cache后：{fib(10)}')
    print(cache)

    avg = make_average()
    print(avg(2))
    print(avg(3))
    print(avg(3))
    avg = make_average2()
    print(avg(2))
    print(avg(3))
    print(avg(3))

    res = foo()
    print(next(res))
    print(next(res))
    print(next(res))
